package com;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import com.Communicator;
import com.Configurator;

public class Communicator {
	private static int port;
	private static int numThreads;
	private static String root = "";
	public static ServerSocket ss;
	private static String xmlConfigPath = ".\\config\\config.xml";
	private static boolean WebServerMode = true;
	private static boolean trayMode = true;
	private static boolean ContinCycle = true;

	public static boolean getTrayMode() {
		return trayMode;
	}

	public static void setTrayMode(boolean trayMode) {
		Communicator.trayMode = trayMode;
	}

	public static boolean getContinCycle() {
		return ContinCycle;
	}

	public static void setContinCycle(boolean ContinCycle) {
		Communicator.ContinCycle = ContinCycle;
	}

	public static int getPort() {
		return port;
	}

	public static void setPort(int port) {
		Communicator.port = port;
	}

	public static void setXmlConfigPath(String xmlConfigPath) {
		Communicator.xmlConfigPath = xmlConfigPath;
	}

	public static String getXmlConfigPath() {
		return xmlConfigPath;
	}

	public static void setWebServerMode(boolean webServerMode) {
		WebServerMode = webServerMode;
	}

	public static boolean getWebServerMode() {
		return WebServerMode;
	}

	public static int getNumThreads() {
		return numThreads;
	}

	public static void setNumThreads(int numThreads) {
		Communicator.numThreads = numThreads;
	}

	public static String getRoot() {
		return root;
	}

	public static void setRoot(String root) {
		Communicator.root = root;
	}

	public static void init(Configurator p) {

		setPort(p.getPort());
		setNumThreads(p.getNumberThread());
		setRoot(p.getRootDirectory());
	}

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		boolean flag = true;
		Configurator p = new Configurator(xmlConfigPath);
		init(p);
		TaskFinder taskFinder = new TaskFinder(p.getNumberThread());
		Tray.createAndShowGUI(taskFinder);
		Thread threadTaskFinder = new Thread(taskFinder);
		threadTaskFinder.start();

		while (getTrayMode()) {			

			ss = new ServerSocket(port);
			System.out.println("Started: " + ss);			

			try {
				while (getWebServerMode()) {
					Socket socket = ss.accept();

					if (!flag) {
						setContinCycle(true);
					}

					if (getContinCycle()) {

						try {
							System.out
									.println("Connection accepted: " + socket);

							taskFinder.add(new Execution(socket));

						} finally {
							System.out.println("closing...");
						}
					} else {
						flag = false;
						break;
					}
				}

			} finally {
				ss.close();
			}
		}
	}
}
